package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IRateRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeysUtil;
import cn.wolfcode.luowowo.website.util.NetworkUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防刷:做防止用户 在同一时间段内多次访问次数
 */
public class RateInterceptor implements HandlerInterceptor {

    @Reference
    private IRateRedisService rateRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果是ajax请求直接放行
        String header = request.getHeader("x-requested-with");
        if (header != null) {
            return true;
        }
        // 获取用户的 ip地址
        String ipAddress = NetworkUtil.getIpAddress(request);
        // 获取用户访问的 url
        String uri = request.getRequestURI();

        // 获取key
        String key = RedisKeysUtil.USER_OPERATION_NUMBER.join(ipAddress, uri);

        // 判断用户 操作频率是否符合要求
        boolean moreThanVisits = rateRedisService.isMoreThanVisits(key);
        // 增加用户的操作次数
        rateRedisService.addUserOperationNumber(key);
        if (moreThanVisits) {
            return true;
        }
        // x-requested-with
        // 判断 请求是和中请求
        //String header = request.getHeader("x-requested-with");
        request.getRequestDispatcher("/frequency/frequency_error.html").forward(request, response);
        return false;
    }
}
